//
//  RankListViewController.m
//  PlayCatchGame
//
//  Created by 流言 on 2018/1/15.
//  Copyright © 2018年 清正. All rights reserved.
//

#import "RankListViewController.h"
#import "AppHeader.h"

#import "RankSectionView.h"
#import "RankListCell.h"

#import "UserAccountModel.h"
#import "UserModel.h"

@interface RankListViewController () <UITableViewDelegate, UITableViewDataSource> {
    
    NSInteger currentPage;
}

@property (weak, nonatomic) IBOutlet UILabel *moneyLabel;
@property (weak, nonatomic) IBOutlet UILabel *countLabel;
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) NSMutableArray<UserAccountModel *> *dataArray;

@end

@implementation RankListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    currentPage = 1;
    self.dataArray =[NSMutableArray array];
    
//    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        currentPage = 1;
        [self.tableView.mj_footer setState:MJRefreshStateIdle];
        [self.dataArray removeAllObjects];
        [self.tableView reloadData];
        [self _getTopChartsShowingHud:NO];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingBlock:^{
        currentPage++;
        [self _getTopChartsShowingHud:NO];
    }];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
    [self _getAccountInfo];
}

#pragma mark - Request Network
- (void)_getTopChartsShowingHud:(BOOL)isShow {
    [HttpUrl NetErrorGET:@"userAccount/selectOrderBy" dict:@{@"current":@(currentPage)} hud:self.view isShow:isShow WithSuccessBlock:^(id data) {
        [self.tableView.mj_footer endRefreshing];
        
        if (BB_isSuccess) {
            NSArray *dataList = data[@"data"];
            if (dataList.count == 0) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                return ;
            }
            [dataList enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                UserAccountModel *userAccountModel = [UserAccountModel mj_objectWithKeyValues:obj];
                [self.dataArray addObject:userAccountModel];
            }];
            [self.tableView.mj_header endRefreshing];
            [self.tableView reloadData];
            
        } else {
            [self.tableView.mj_header endRefreshing];
            ShowAlertTitle(data[@"msg"]?data[@"msg"]:@"获取数据失败");
        }
    } WithFailBlock:^(id data) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        ShowAlertTitle(@"网络连接错误");
    }];

}

- (void)_getAccountInfo {
    [HttpUrl GET:@"userAccount/selectMyAccount" dict:nil hud:self.view isShow:NO WithSuccessBlock:^(id data) {
        if (BB_isSuccess) {
            
            UserAccountModel *myAccountModel = [UserAccountModel mj_objectWithKeyValues:data[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.moneyLabel.text = [NSString stringWithFormat:@"%.2f", myAccountModel.profitMoney];
                self.countLabel.text = [NSString stringWithFormat:@"%ld", myAccountModel.winTimes];
            });
            
            
        } else {
            ShowAlertTitle(data[@"msg"]);
        }
    }];
    
    
}

#pragma mark - Action Method
- (void)headerRefresh {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        currentPage = 1;
        [self.tableView.mj_footer setState:MJRefreshStateIdle];
        [self.dataArray removeAllObjects];
        [self _getTopChartsShowingHud:YES];
    });

    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 44)];
    headerView.backgroundColor =tableView.backgroundColor;

    UIView *view =[RankSectionView loadNib:@"RankSectionView" frame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 44)];
    view.backgroundColor =[UIColor clearColor];
    [headerView addSubview:view];
    
    return headerView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RankListCell *cell =[tableView dequeueReusableCellWithIdentifier:@"RankListCell"];

    if (!cell) {
        cell =[RankListCell findCellWithIdentifier:@"RankListCell"];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
    }
    
    UserAccountModel *model = self.dataArray[indexPath.row];
    cell.index =indexPath.row;
    [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:model.user.headImg] placeholderImage:[UIImage imageNamed:@"small_touxiang"]];
    cell.nameLabel.text = model.user.userName;
    cell.moneyLabel.text = [NSString stringWithFormat:@"¥%.2lf", model.profitMoney];
    cell.countLabel.text = [NSString stringWithFormat:@"%ld", model.winTimes];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
